package com.shaoshaohuo.app.ui.ec;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.adapter.MarketListAdapter;
import com.shaoshaohuo.app.adapter.SellerListAdapter;
import com.shaoshaohuo.app.constant.ExtraName;
import com.shaoshaohuo.app.constant.ListViewAction;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.BusinessBuyer;
import com.shaoshaohuo.app.entity.BusinessBuyersEntity;
import com.shaoshaohuo.app.entity.BusinessSeller;
import com.shaoshaohuo.app.entity.BusinessSellerEntity;
import com.shaoshaohuo.app.entity.EcCategorySecond;
import com.shaoshaohuo.app.entity.EcCategoryThird;
import com.shaoshaohuo.app.net.HttpRequest.RequestListener;
import com.shaoshaohuo.app.net.RequestService;
import com.shaoshaohuo.app.ui.BaseActivity;
import com.shaoshaohuo.app.utils.Location2Util;
import com.shaoshaohuo.app.utils.city.Cityinfo;
import com.shaoshaohuo.app.view.TopbarView;
import com.shaoshaohuo.app.view.XListView;
import com.shaoshaohuo.app.view.XListView.IXListViewListener;
import com.shaoshaohuo.app.view.citymenu.CascadingMenuPopWindow;
import com.shaoshaohuo.app.view.citymenu.entity.Area;
import com.shaoshaohuo.app.view.citymenu.interfaces.CascadingMenuViewOnSelectListener;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName BusinessOpportunityActivity
 * @author linmu
 * @Decription 商机 @2015-8-28 下午10:29:47
 */
public class BusinessOpportunityActivity extends BaseActivity implements OnClickListener, IXListViewListener {

    private static final int SELECT_PRODUCT_TYPE = 1;
    private static final int SELECT_MARKET_CITY = SELECT_PRODUCT_TYPE + 1;
    
    private TopbarView mTopbarView;

    private TextView mLeftTabText;
    private TextView mRightTabText;

    private TextView mAreaText;
	private TextView mTypeText;
    
    private LinearLayout mContentLayout;

    private View mBuyersLayout;
    private View mSellerLayout;

    private TextView mCurrentCityText;
    private TextView mNearbyMarketText;
    private XListView mMarketListview;

    private TextView mShangjiCountText;
    private XListView mSellersListview;
    
    private MarketListAdapter<BusinessBuyer> mBuyerAdapter;
    private SellerListAdapter<BusinessSeller> mSellerAdapter;
    private List<BusinessSeller> mSellerData = new ArrayList<BusinessSeller>();
    private List<BusinessBuyer> mBuyerData = new ArrayList<BusinessBuyer>();
    
    private String bigpid = "";
    private String catid = "";
    private String pid = "";
    private String cityid = "";
    private String action = ListViewAction.NEW2;
    private String cursor = "";
    private int offset = 10;
    
    protected List<EcCategoryThird> mVarietyList;
    private EcCategorySecond ecCategorySecond;
//    private Province selectProvince;
//    private City selectCity;
	private Cityinfo selectProvince;// 选中的省
	private Cityinfo selectCity; // 选中的市

    private boolean isMarketStatus = false; //默认找买家，为true；默认找卖家为false
    
    private int size1 = 10;
    private String cursor1 = "";
    private String action1 = ListViewAction.NEW;
//    private String proid1 = "";
//    private String citycode1 = "";
    private String lng1 = "";
    private String lat1 = "";
    private String  long1 = "";
    private int buyersize1 = 4;
    private String shuai = "0";
    
    private String nearByCity = "";
    
    private CascadingMenuPopWindow cascadingMenuPopWindow;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        setContentView(new TopbarView(this));
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                setContentView(R.layout.activity_business_opportunity);
                initView();
                setUpView();
            }
        }, 200);
    }

    private void initLocation(){
        Location2Util instance = Location2Util.getInstance(this);
        instance.setOnLocationListener(new Location2Util.OnLocationListener() {

            @Override
            public void onLocationSuccess(AMapLocation location) {
                nearByCity = location.getCity();
                lng1 = location.getLongitude()+"";
                lat1 = location.getLatitude()+"";
            }
        });
        instance.startLocation();
    }
    
    private void initView() {
        mTopbarView = (TopbarView) this.findViewById(R.id.topbar);

        mLeftTabText = (TextView) this.findViewById(R.id.textview_tab_left);
        mRightTabText = (TextView) this.findViewById(R.id.textview_tab_right);
        mContentLayout = (LinearLayout) this.findViewById(R.id.layout_content);
        
        mAreaText = (TextView) this.findViewById(R.id.textview_tab_diqu);
		mTypeText = (TextView) this.findViewById(R.id.textview_tab_pinzhong);
        
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                addSellersLayout();
            }
        }, 200);
    }

    private void setUpView() {
        mTopbarView.setCenterText("商机");
        mTopbarView.setLeftView(true, true);
//        mTopbarView.setRightText("分类");
//        mTopbarView.setRightClickListener(new OnClickListener() {
//
//            @Override
//            public void onClick(View v) {
//                Intent intent = new Intent(BusinessOpportunityActivity.this, ProductTypeActivity.class);
//                startActivityForResult(intent, 0);
//            }
//        });

        mLeftTabText.setOnClickListener(this);
        mRightTabText.setOnClickListener(this);
        mLeftTabText.setSelected(false);
        mRightTabText.setSelected(true);
        
        mAreaText.setOnClickListener(this);
        mTypeText.setOnClickListener(this);
        mTypeText.setVisibility(View.GONE);
//        setListView();
    }

    protected void addBuyersLayout() {
        if (mBuyersLayout == null) {
            mBuyersLayout = View.inflate(this, R.layout.layout_find_buyers, null);

            mCurrentCityText = (TextView) mBuyersLayout.findViewById(R.id.textview_current_city);
            mNearbyMarketText = (TextView) mBuyersLayout.findViewById(R.id.textview_nearby_market);
            mMarketListview = (XListView) mBuyersLayout.findViewById(R.id.listview_market_list);

            
            mNearbyMarketText.setVisibility(View.GONE);
            
            mMarketListview.setPullLoadEnable(true);
            mMarketListview.setPullRefreshEnable(true);
            mMarketListview.setXListViewListener(this);

            mMarketListview.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    BusinessBuyer supply = (BusinessBuyer) parent.getItemAtPosition(position);
                    Intent intent = new Intent(BusinessOpportunityActivity.this, MarketDetailActivity.class);
                    intent.putExtra(ExtraName.id, supply.getMarketid());
                    intent.putExtra(ExtraName.marketName, supply.getMarketname());
                    startActivity(intent);
                }
            });
            
//            findBuyerList(true);
            getLocation();
        }


        mContentLayout.removeAllViews();
        mContentLayout.addView(mBuyersLayout);
    }

    private void getLocation() {
        Location2Util instance = Location2Util.getInstance(this);
        instance.setOnLocationListener(new Location2Util.OnLocationListener() {

            @Override
            public void onLocationSuccess(AMapLocation location) {
                mCurrentCityText.setText(location.getCity());
            }
        });
        instance.startLocation();
    }

    protected void addSellersLayout() {
        if (mSellerLayout == null) {
            mSellerLayout = View.inflate(this, R.layout.layout_find_seller, null);

            mShangjiCountText = (TextView) mSellerLayout.findViewById(R.id.textview_shangji_count);
            mSellersListview = (XListView) mSellerLayout.findViewById(R.id.listview_data_list);

            
            mSellersListview.setPullLoadEnable(true);
            mSellersListview.setPullRefreshEnable(true);
            mSellersListview.setXListViewListener(this);
            
            mSellersListview.setOnItemClickListener(new OnItemClickListener() {
                
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    BusinessSeller supply = (BusinessSeller) parent.getItemAtPosition(position);
                    Intent intent = new Intent(BusinessOpportunityActivity.this, SupplierDetailActivity.class);
                    intent.putExtra(ExtraName.id, supply.getId());
                    startActivity(intent);
                }
            });
            findSellerList(true);
        }

        mContentLayout.removeAllViews();
        mContentLayout.addView(mSellerLayout);
    }



    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.textview_tab_left:
            if (mLeftTabText.isSelected()) {
                return;
            }
            mLeftTabText.setSelected(true);
            mRightTabText.setSelected(false);
            mTypeText.setVisibility(View.GONE);

            addBuyersLayout();
            isMarketStatus = true;
            refrensh();
            //isMarketStatus = true;
            break;
        case R.id.textview_tab_right:
            if (mRightTabText.isSelected()) {
                return;
            }
            mLeftTabText.setSelected(false);
            mRightTabText.setSelected(true);
            mTypeText.setVisibility(View.VISIBLE);
            addSellersLayout();

            isMarketStatus = false;
            refrensh();
            break;
        case R.id.textview_tab_diqu:
        	selectCity();
			break;
		case R.id.textview_tab_pinzhong:
			selectProduct();
			break;
        }
    }
    
    private void selectCity() {
//    	new CascadingMenuPopWindow().showInstance(this, mRightTabText, new NMCascadingMenuViewOnSelectListener());
    	if (cascadingMenuPopWindow == null) {
			//向三级menu添加地区数据
			cascadingMenuPopWindow = new CascadingMenuPopWindow(this);
			cascadingMenuPopWindow
					.setMenuViewOnSelectListener(new NMCascadingMenuViewOnSelectListener());
			cascadingMenuPopWindow.showAsDropDown(mRightTabText, 5, 5);
		} else if (cascadingMenuPopWindow != null
				&& cascadingMenuPopWindow.isShowing()) {
			cascadingMenuPopWindow.dismiss();
		} else {
			cascadingMenuPopWindow.showAsDropDown(mRightTabText, 5, 5);
		}
    }
	
	class NMCascadingMenuViewOnSelectListener implements
			CascadingMenuViewOnSelectListener {

		@Override
		public void getValue(Area city, String fullname) {
//			selectCity = CityinfoUtil.convert(city);
			if (selectCity == null) {
				mAreaText.setText(fullname);
			} else {
				mAreaText.setText(selectCity.getCity_name());
			}
			refrensh();
		}

	}
    
	private void selectProduct() {
		Intent intent = new Intent(this, ProductTypeActivity.class);
		startActivityForResult(intent, SELECT_PRODUCT_TYPE);
	}
    

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
            case SELECT_PRODUCT_TYPE:
                EcCategorySecond second = (EcCategorySecond) data.getSerializableExtra(ExtraName.ecCategorySecond);
//                if(ecCategorySecond != null && !TextUtils.isEmpty(ecCategorySecond.getCatid()) && ecCategorySecond.getCatid().equals(second.getCatid())){
//                }else{
//
//                    if(ecCategorySecond != null && second.getCatname().equals("全部") && ecCategorySecond.getCatname().equals("全部") ){
//                        return;
//                    }
//                    ecCategorySecond = second;
//                    bigpid = ecCategorySecond.getBigpid();
//                    pid = ecCategorySecond.getCatid();
//                    mTypeText.setText(ecCategorySecond.getCatname());
                    refrensh();
                    mVarietyList = null;
//                    if(!ecCategorySecond.getCatname().equals("全部")){
//                        getVariety(ecCategorySecond);
//                    }
//                }
                break;
            
            /*case SELECT_MARKET_CITY:
                selectProvince = (Province) Data.getSerializableExtra(ExtraName.province);
                selectCity = (City) Data.getSerializableExtra(ExtraName.city);
                mAreaText.setText(selectCity.getCityname());
                refrensh();
            	
            	
            	
                break;
                }*/
            }
        }
    }
    
    
    private void refrensh() {
    	if(isMarketStatus){
    		mBuyerData.clear();
    	}else{
    		mSellerData.clear();
    	}
        onRefresh();
    }
    
    private void findSellerList(boolean isLoading) {
        if (isLoading) {
            startLoadingDialog();
        }
		if (selectCity != null) {
			cityid = selectCity.getId();
		} else {
			cityid = null;
		}
        RequestService.getInstance().findSellerList(this, cursor, offset+"", action, bigpid, pid, catid, cityid, BusinessSellerEntity.class,
                new RequestListener() {

                    @Override
                    public void onSuccess(int requestCode, BaseEntity resultData) {
                        dismissLoadingDialog();
                        if (resultData.isOk()) {
                            BusinessSellerEntity entity = (BusinessSellerEntity) resultData;
                            List<BusinessSeller> list = entity.getData().getList();
                            mSellerData.addAll(list);

                            if ((mSellerData.size() < offset) || (action.equals(ListViewAction.HISTORY2) && list.size() < offset)) {
                                // mSellersListview.setPullLoadEnable(false);
                                mSellersListview.endLoadingMore("没有更多了");
                            }
                            
                            mShangjiCountText.setText("今日发布"+entity.getData().getTodaypublish()+"条商机");
                            
                            setSellerAdapter(mSellerData);

                        } else {
                            showToast(resultData.getMsg());
                        }
                        onLoad();
                    }

                    @Override
                    public void onFailed(int requestCode, Exception error, String msg) {
                        dismissLoadingDialog();
                        showToast(msg);
                        onLoad();
                    }
                });
    }

    protected void setBuyersAdapter(List<BusinessBuyer> mSellerData2) {
        if (mBuyerAdapter == null) {
            mBuyerAdapter = new MarketListAdapter<BusinessBuyer>(this, mSellerData2, false);
            mMarketListview.setAdapter(mBuyerAdapter);
        } else {
            mBuyerAdapter.setData(mSellerData2);
        }
    }
    protected void setSellerAdapter(List<BusinessSeller> mSellerData2) {
        
        if (mSellerAdapter == null) {
            mSellerAdapter = new SellerListAdapter<BusinessSeller>(this, mSellerData2, false);
            mSellersListview.setAdapter(mSellerAdapter);
        } else {
            mSellerAdapter.setData(mSellerData2);
        }
    }
    
    private void findBuyerList(boolean isLoading) {
        if (isLoading) {
            startLoadingDialog();
        }
		if (selectCity != null) {
			cityid = selectCity.getId();
		} else {
			cityid = null;
		}
        
        initLocation();
        RequestService.getInstance().findBuyersList(this, size1+"", cursor1, action1, cityid, lng1, lat1, long1, buyersize1+"", BusinessBuyersEntity.class,
                        new RequestListener() {
            
            @Override
            public void onSuccess(int requestCode, BaseEntity resultData) {
                dismissLoadingDialog();
                if (resultData.isOk()) {
                    BusinessBuyersEntity entity = (BusinessBuyersEntity) resultData;
                    List<BusinessBuyer> list = entity.getData().getList();
                    mBuyerData.addAll(list);
                    
                    if ((mBuyerData.size() < size1) || (action1.equals(ListViewAction.HISTORY) && list.size() < size1)) {
                        // mSellersListview.setPullLoadEnable(false);
                        mMarketListview.endLoadingMore("没有更多了");
                    }
                    setBuyersAdapter(mBuyerData);
                    
                } else {
                    showToast(resultData.getMsg());
                }
                onLoad();
            }
            
            @Override
            public void onFailed(int requestCode, Exception error, String msg) {
                dismissLoadingDialog();
                showToast(msg);
                onLoad();
            }
        });
    }
    

    
//    private void setListView() {
//       
//    }

    @Override
    public void onRefresh() {
        if(isMarketStatus){
            if (mBuyerData.size() > 0) {
                cursor1 = mBuyerData.get(0).getCursor();
            } else {
                cursor1 = "";
            }
            action1 = ListViewAction.NEW;
            mMarketListview.setPullLoadEnable(true);
            findBuyerList(false);
        }else{
            if (mSellerData.size() > 0) {
                cursor = mSellerData.get(0).getCursor();
            } else {
                cursor = "";
            }
            action = ListViewAction.NEW2;
            mSellersListview.setPullLoadEnable(true);
            findSellerList(false);
        }
    }

    @Override
    public void onLoadMore() {
        if(isMarketStatus){
            if (mBuyerData.size() > 0) {
                cursor1 = mBuyerData.get(mBuyerData.size() - 1).getCursor();
            } else {
                cursor1 = "";
            }
            action1 = ListViewAction.HISTORY;
            findBuyerList(false);
        }else{
            if (mSellerData.size() > 0) {
                cursor = mSellerData.get(mSellerData.size() - 1).getCursor();
            } else {
                cursor = "";
            }
            action = ListViewAction.HISTORY2;
            findSellerList(false);
        }
    }

    private void onLoad() {
        if(isMarketStatus){
            mMarketListview.stopRefresh();
            mMarketListview.stopLoadMore();
        }else{
            mSellersListview.stopRefresh();
            mSellersListview.stopLoadMore();
        }
    }
    @Override
	protected void onDestroy() {
		if (cascadingMenuPopWindow != null) {
			cascadingMenuPopWindow.dismiss();
		}
		super.onDestroy();
	}
}
